from typing import Iterable
import numpy as np

from visualize import showData

def getNextPosition(ss:Iterable, i:int)->int:
    while i<len(ss):
        if ss[i]=='AA' and ss[i+1]=='AA' and ss[i+2]=='F1':
            return i
        i += 1


def parseInt(ss:Iterable)->int:
    s = ''.join(ss)
    num = int(s, 16)
    if num > ((1<<31) - 1):
        num -= (1<<32)
    return num

class FileStream:
    def __init__(self, path, smooth = True):
        self.path = path
        self.smooth = smooth

    def loadFile(self):  # 读整个数据，返回二维list  n*8
        ss = None
        with open(self.path, "r") as fin:
            s = fin.read()
            ss = s.split(' ')
        # 处理数据
        start = 0
        packageLen = 38
        pre = None

        ret = []
        while True:
            start = getNextPosition(ss, start)
            if start is None or start + packageLen > len(ss): break
            channels = [parseInt(ss[i:i+4]) for i in range(start+4, start+36, 4)]

            if self.smooth:
                channels = np.asarray(channels)
                if pre is not None:
                    channels = 0.2 * pre + 0.8 * channels
                pre = channels
                channels = channels.tolist()

            ret.append(channels)
            start += packageLen
        
        return ret

    def __iter__(self):  # 支持把此类对象作为一个可迭代的容器使用
        this = self
        class Iter:
            def __init__(self):
                self.data = this.loadFile()
                self.idx = 0
                self.pre = None

            def __next__(self):
                if self.idx >= len(self.data):
                    raise StopIteration
                ret = self.data[self.idx]

                # 平滑
                ret = np.asarray(self.data[self.idx])
                if this.smooth:
                    if self.pre is not None:
                        ret = 0.3 * self.pre + 0.7 * ret
                    pre = ret
                
                self.idx += 1
                return ret
                
        return Iter()

if __name__ == "__main__":
    path = "./data/new_data.txt"

    fileStream = FileStream(path);

    # 测试对象的迭代
    # i = 0
    # for row in fileStream:
    #     print(row)
    #     i = i + 1
    #     if i == 100:
    #         break;

    
    data = fileStream.loadFile()
    showData(data)
